//
//  BeautyViewController.m
//  YMJReadColor
//
//  Created by 殷殷明静 on 16/9/10.
//  Copyright © 2016年 MJ.Y. All rights reserved.
//

#import "BeautyViewController.h"
#import "DetailViewController.h"
#import "HomeViewController.h"
#import "MainViewController.h"
#import "HomeTableViewCell.h"
#import "HomeTableViewSecondCell.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "YMJMacro_h.h"
#import "DataModel.h"
#import "Model.h"
#import "UIScrollView+JHRefresh.h"
#import "JHRefreshAmazingAniView.h"

#define BEAUTIFUL @"beautiful"
#define BEAUTIFULP @"beautiful.plist"
@interface BeautyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) HomeViewController *homeVC;
@end

@implementation BeautyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createView];
    [self refresh];
}
- (void)createView {
    // 获得viewController
    UIWindow *windows = [[UIApplication sharedApplication]keyWindow];
    MainViewController *tab= (MainViewController *)windows.rootViewController;
    UINavigationController *homenavc = (UINavigationController *)[tab.viewControllers firstObject];
    _homeVC = (HomeViewController *)[homenavc.viewControllers firstObject];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 108) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"1"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeTableViewSecondCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"2"];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DataModel *data = _dataArray[indexPath.row];
    if (data.imageDTOList.count == 2) {
        return 180;
    } else {
        return 76;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DataModel *data = _dataArray[indexPath.row];
    if (data.imageDTOList.count == 2) {
        HomeTableViewSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:@"2"];
        cell.myImageView.contentMode = UIViewContentModeScaleAspectFill;
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[data.imageDTOList lastObject].src]];
        cell.myTitleLabel.text = data.title;
        cell.myOriginLabel.text = data.origin;
        
        return cell;
    } else {
        HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[data.imageDTOList lastObject].src]];
        cell.myTitleLabel.text = data.title;
        cell.myOriginLabel.text = data.origin;
        return cell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detailVC = [DetailViewController new];
    DataModel *data = self.dataArray[indexPath.row];
    detailVC.messageId = data.messageId;
    detailVC.categoryIds = data.categoryIds;
    detailVC.infomation = data.title;
    detailVC.parentId = data.parentId;
    detailVC.parentType = data.parentType;
    detailVC.messageType = data.messageType;
    /*收藏*/
    detailVC.newsId = data.messageId;
    detailVC.newsType = data.messageType;
    detailVC.newsEngineType = data.engineType;
    detailVC.layoutType = data.layoutType;
    [self.homeVC setHidesBottomBarWhenPushed:YES];
    [self.homeVC.navigationController pushViewController:detailVC animated:YES];
    [self.homeVC setHidesBottomBarWhenPushed:NO];
    
}

- (void)refresh {
    /*缓存沙盒路径 */
    NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    /*首页文件夹*/
    NSFileManager*fileManager = [NSFileManager defaultManager];
    NSString *homePath = [cache stringByAppendingPathComponent:@"homeNews"];
    BOOL res = [fileManager createDirectoryAtPath:homePath withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        /*推荐子文件夹*/
        NSString *domestricPath = [homePath stringByAppendingPathComponent:BEAUTIFUL];
        BOOL res1 = [fileManager createDirectoryAtPath:domestricPath withIntermediateDirectories:YES attributes:nil error:nil];
        if (res1) {
            /*存入数据*/
            NSString *path = [domestricPath stringByAppendingPathComponent:BEAUTIFULP];
            /*先读出沙盒文件*/
            BOOL res1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if (res1) {
                /*读取文件*/
                _dataArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
                /*如果数量多于30个,只要前30个*/
                if (_dataArray.count > 30) {
                    for (int i = 31; i < _dataArray.count; i++) {
                        [_dataArray removeObjectAtIndex:i];
                    }
                }
            }
            
        }
        
    }

    
    
    __weak BeautyViewController *weakSelf = self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshAmazingAniView class] beginRefresh:^{
        // 延时2秒再刷新
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            YMJNetWorking *gns = [YMJNetWorking shareNetWorking];
            if (![gns updateInterfaceWithReachability]) {
                [weakSelf.tableView headerEndRefreshingWithResult:JHRefreshResultFailure];
            } else {
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Sdk/0.2.0 (agent:s;channel:venus;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
                [manager.requestSerializer setValue:@"api.9wuli.com" forHTTPHeaderField:@"Host"];
                [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
                [manager GET:@"http://api.9wuli.com/v1/message/summary?channelId=4405fdb64e27601b202504e949c417bd&pageSize=6&since=1473490065710&slipType=DOWN&appId=15cba93584fa09ed2873fefcdc9b08c9&appSecret=49759a039852e3f826d8754f0b13cb47" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSDictionary *dic = responseObject;
                    Model *mo = [Model modelWithDic:dic];
                    NSMutableArray *downArray = [NSMutableArray arrayWithArray:mo.data];
                    if (downArray.count == 0) {
                        [weakSelf.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess dataCount:downArray.count];
                    } else {
                        [weakSelf.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess dataCount:downArray.count];
                        NSArray *currentArray = weakSelf.dataArray;
                        [downArray addObjectsFromArray:currentArray];
                        weakSelf.dataArray = downArray;
                        [weakSelf.tableView reloadData];
                        /*存入首次数据*/
                        /*存入数据*/
                        NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
                        NSString *homePath = [cache stringByAppendingPathComponent:@"homeNews"];
                        NSString *recommendPath = [homePath stringByAppendingPathComponent:BEAUTIFUL];
                        NSString *path = [recommendPath stringByAppendingPathComponent:BEAUTIFULP];
                        [NSKeyedArchiver archiveRootObject:weakSelf.dataArray toFile:path];
                    }
                    
                    
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    
                }];
            }
            
            
        });
        
    }];
    // 上拉刷新
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshAmazingAniView class] beginRefresh:^{
        // 生成随机数
        int rand = (4 + arc4random() % (6 - 4 + 1));
        // 生成时间戳
        NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a = [dat timeIntervalSince1970] * 1000;
        NSString *timeString = [NSString stringWithFormat:@"%.0f",a];
        NSString *randURL = [NSString stringWithFormat:@"http://api.9wuli.com/v1/message/summary?channelId=4405fdb64e27601b202504e949c417bd&pageSize=%d&since=%@&slipType=UP&appId=15cba93584fa09ed2873fefcdc9b08c9&appSecret=49759a039852e3f826d8754f0b13cb47",rand,timeString];
        // 延时2秒再刷新
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Sdk/0.2.0 (agent:s;channel:venus;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
            [manager.requestSerializer setValue:@"api.9wuli.com" forHTTPHeaderField:@"Host"];
            [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
            [manager GET:randURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = responseObject;
                Model *mo = [Model modelWithDic:dic];
                NSArray *dataArr = [NSArray arrayWithArray:mo.data];
                if (dataArr.count == 0) {
                    [weakSelf.tableView footerEndRefreshing];
                } else {
                    [weakSelf.dataArray addObjectsFromArray:dataArr];
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView footerEndRefreshing];
                    /*存入数据*/
                    NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
                    NSString *homePath = [cache stringByAppendingPathComponent:@"homeNews"];
                    NSString *recommendPath = [homePath stringByAppendingPathComponent:BEAUTIFUL];
                    NSString *path = [recommendPath stringByAppendingPathComponent:BEAUTIFULP];
                    [NSKeyedArchiver archiveRootObject:weakSelf.dataArray toFile:path];
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
            }];
            
        });
        
    }];
    [_tableView headerStartRefresh];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([scrollView isEqual:_tableView]) {
        if (scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height) {
            int rand = (4 + arc4random() % (6 - 4 + 1));
            // 生成时间戳
            NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
            NSTimeInterval a = [dat timeIntervalSince1970] * 1000;
            NSString *timeString = [NSString stringWithFormat:@"%.0f",a];
            NSString *randURL = [NSString stringWithFormat:@"http://api.9wuli.com/v1/message/summary?channelId=4405fdb64e27601b202504e949c417bd&pageSize=%d&since=%@&slipType=UP&appId=15cba93584fa09ed2873fefcdc9b08c9&appSecret=49759a039852e3f826d8754f0b13cb47",rand,timeString];
            // 立即刷新
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Sdk/0.2.0 (agent:s;channel:venus;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
            [manager.requestSerializer setValue:@"api.9wuli.com" forHTTPHeaderField:@"Host"];
            [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
            [manager GET:randURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = responseObject;
                Model *mo = [Model modelWithDic:dic];
                NSArray *dataAr = [NSArray arrayWithArray:mo.data];
                [self.dataArray addObjectsFromArray:dataAr];
                [self.tableView reloadData];
                /*存入数据*/
                NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
                NSString *homePath = [cache stringByAppendingPathComponent:@"homeNews"];
                NSString *recommendPath = [homePath stringByAppendingPathComponent:BEAUTIFUL];
                NSString *path = [recommendPath stringByAppendingPathComponent:BEAUTIFULP];
                [NSKeyedArchiver archiveRootObject:self.dataArray toFile:path];
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
            }];
            
            
            
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */



@end
